package com.z001.snack.common.handler;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.z001.snack.common.common.domain.RequestUser;
import com.z001.snack.common.common.util.SmartRequestUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author szy
 * @Date 2023/7/7 09:38
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    /**
     * 插入元对象字段填充（用于插入时对公共字段的填充）
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "rowStatus", Integer.class, 10);

        //获取当前用户
        RequestUser requestUser = SmartRequestUtil.getRequestUser();
        if(ObjectUtil.isNotEmpty(requestUser)){
            this.strictInsertFill(metaObject, "createUser", Long.class, requestUser.getUserId());
            this.strictInsertFill(metaObject, "createUserName", String.class, requestUser.getUserName());
            this.strictInsertFill(metaObject, "updateUser", Long.class,requestUser.getUserId());
            this.strictInsertFill(metaObject, "updateUserName", String.class, requestUser.getUserName());

        }
    }

    /**
     * 更新元对象字段填充（用于更新时对公共字段的填充）
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        //获取当前用户
        RequestUser requestUser = SmartRequestUtil.getRequestUser();
        if(ObjectUtil.isNotEmpty(requestUser)){
            this.strictInsertFill(metaObject, "createUser", Long.class, requestUser.getUserId());
            this.strictInsertFill(metaObject, "createUserName", String.class, requestUser.getUserName());
            this.strictInsertFill(metaObject, "updateUser", Long.class,requestUser.getUserId());
            this.strictInsertFill(metaObject, "updateUserName", String.class, requestUser.getUserName());
        }
    }
}
